#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2022-11-01 14:06:58
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$
import sys
import time
import network
# from aioespnow import espnow
import espnow
import ubinascii
import machine

#把字符串的mac地址转成可使用的字节流
def hexStrToBytes(hex_str):
    # hex_string = 'ffffffffffff'
    print(hex_str)
    byte_string = ubinascii.unhexlify(hex_str)
    return byte_string

def bytesToHexStr(bs):
    hex_str = ubinascii.hexlify(bs)
    return hex_str.decode()

sendList = {}   #已发送数据缓存
e = None
thisMac = ''

def checkSendBack(cbmsg,scrc):
    sends = scrc.split(',')
    sdat = sends[0]
    crc = sends[1]
    if cbmsg == scrc:
        return True
    return False

#1 [b'\x86\r\x8e\x99\xdb\xc0', bytearray(b'getcmd')]
#返回接收到的数据数量和数据值数组
def recv_cb(n,msg):
    global sendList,e
    v = msg
    if v[0] in sendList:
        hoststr = bytesToHexStr(msg[0])
        datmsg = msg[1].decode().replace(':','').replace('\r','').replace('\n','').replace(' ','').replace('\t','')
        if checkSendBack(v[1].decode(),sendList[v[0]]):
            print(bytesToHexStr(v[0]),1)
            sendList.pop(v[0])
            e.del_peer(v[0])
            return
        else:
            print(bytesToHexStr(v[0]),v[1].decode())
            sendList.pop(v[0])
            e.del_peer(v[0])
            return
    else:
        print(bytesToHexStr(msg[0])+'-' + msg[1].decode())

def readUART():
    dstr = sys.stdin.readline().replace('\n','')
    if type(dstr) != str:
        return dstr.decode()
    return dstr

def crcCheck(dats):
    crc = 0
    for i,v in enumerate(dats):
        crc += ord(v)
    outcrc = crc%0x0ff
    return str(outcrc)

#串口中读到什么就把什么分发出去
#串口会得到要发送的数据目标mac地址数组,以及要发送的数据
#串口收到的数据会是:mac地址|数据
#mac地址字符串,数据
def getSendCmd():
    serdat = readUART()
    if serdat[0] == 't':
        print(thisMac)
        return None,None
    elif serdat[0] == '$':
        machine.reset()
    nindex = serdat.find('-')
    macdat = serdat[:nindex]
    dats = serdat.split('-')
    if macdat.find(':') != -1:
        macdat = macdat.replace(':','')
    mac = hexStrToBytes(macdat)
    sendat = serdat[nindex+1:]
    return mac,sendat
#开关
def main():
    global sendList,e,thisMac
    #广播只有esp32可以接收和发送广播
    sta = network.WLAN(network.STA_IF)  # Or network.AP_IF
    sta.active(True)
    thisMac = ubinascii.hexlify(sta.config('mac'),':').decode()
    print('mac>' + thisMac)                         #本机mac地址
    sta.disconnect()                   # For ESP8266

    e = espnow.ESPNow()
    e.active(True)
    e.irq(recv_cb)                     #设置接收回调
    # e.config(on_recv = recv_cb)

    #按键检测循环
    while True:
        smac,dstr = getSendCmd()        #从串口读取要发送的目标地址和数据  
        if not smac:
            continue
        if not (smac in sendList):
            e.add_peer(smac)                #把目标地址添加到espnow发送地址中
        dstr += ',' + crcCheck(dstr)   #对要送数据进行crc计算
        sendList[smac] = dstr           #保存已发送数据到保存列表
        e.send(smac, dstr)              #发送数据
        time.sleep_ms(2)
        
if __name__ == '__main__':
    main()